/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package javagprssrv.DataBase;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import org.apache.log4j.Logger;
import redis.clients.jedis.Jedis;

/**
 *
 * @author dusin
 */
public class UpdateHeartBeatThread extends Thread {

    Logger logger = Logger.getLogger(UpdateHeartBeatThread.class);
    DBSQLExecute dbse = new DBSQLExecute();
    private static final int BATCH_SIZE = 10;   //批处理的最大值
    boolean isStop = false;

    public UpdateHeartBeatThread() {
        super("UpdateHeartBeatThread");
    }

    public void run() {
        int i = 0;
        while (!isStop) {
            try {
                i++;
                logger.info("next run " +i);
                Jedis jedis = new Jedis();
                Set<String> keys = jedis.keys("hb.*");
                List<Object[]> beans = new ArrayList<Object[]>();
                for (String k : keys) {
                    String v = jedis.get(k);   //心跳时间
                    String[] kk = k.substring(3).split("#");
                    if(kk[2]==null||"null".equals(kk[2])||"".equals(kk[2])){
                        kk[2]="0";
                    }
                    Object[] b = new Object[]{v, kk[0], kk[1], kk[2]};
                    beans.add(b);
                }
                
                if(!beans.isEmpty()){
                    dbse.doUpdateHeartBeatBatch(beans);
                }
                logger.info("update heart beat for " + beans.size() + " devices");
                for (String k : keys) {
                    jedis.del(k);
                }

                Thread.sleep(180 * 1000);
            } catch (Exception e) {
                e.printStackTrace();
            } catch(Throwable t){
                t.printStackTrace();
            }
        }
    }
}
